package cn.yza.并发.锁.ReentrantLock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Honglixi
 * @create 2021-11-14 14:23
 */
public class LockTest03 {
    private ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        final LockTest03 lockDemo = new LockTest03();

        Thread threada = new Thread("Thread A") {
            @Override
            public void run() {
                lockDemo.doSomeThing2(Thread.currentThread());
            }
        };
        threada.start();

        Thread threadb = new Thread("Thread B") {
            @Override
            public void run() {
                lockDemo.doSomeThing2(Thread.currentThread());
            }
        };
        threadb.start();

        threadb.interrupt();
    }

    public void doSomeThing1(Thread thread) {
        lock.lock();
        try {
            System.out.println(thread.getName() + "得到了锁.");
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(thread.getName() + "释放了锁.");
            lock.unlock();
        }
    }


    public void doSomeThing2(Thread thread) {
        if (lock.tryLock()) {
            try {
                System.out.println(thread.getName() + "得到了锁.");
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println(thread.getName() + "释放了锁.");
                lock.unlock();
            }
        } else {
            System.out.println(thread.getName() + "获取锁失败.");
        }
    }

    public void doSomeThing3(Thread thread) {
        try {
            lock.lockInterruptibly();
            System.out.println(thread.getName() + " 得到了锁.");
            Thread.sleep(6000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
            System.out.println(thread.getName() + " interrupted.");
        } finally {
            System.out.println(thread.getName() + " 释放了锁.");
            lock.unlock();
        }
    }
}
